<!-- 页面 -->
<template>
  <div>
    <el-table :data="userList" border style="width: 100%" class="center-table">
      <el-table-column prop="name" label="用户名" align="center">
        <template #default="scope">
          <span class="ellipsis" :title="scope.row.name">{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="email" label="邮箱" align="center">
        <template #default="scope">
          <span class="ellipsis" :title="scope.row.email">{{ scope.row.email }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="phone" label="电话" align="center"> </el-table-column>
      <el-table-column prop="address" label="地址" align="center"> </el-table-column>
      <el-table-column prop="isManager" label="是否管理员" align="center">
        <template #default="scope">
          <span class="ellipsis" :title="scope.row.isManager">
            <span v-if="scope.row.isManager==1">是</span>
            <span v-else>否</span>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="300" align="center">
        <template #default="scope">
          <el-button size="mini" @click="openEditDialog(scope.row)" v-if="userRole === 'admin'">
            编辑
          </el-button>
          <el-button size="mini" @click="openDetailsDialog(scope.row)">详情</el-button>
          <el-button v-if="userRole === 'admin'" size="mini" @click="editDetailsDialog(scope.row)">修改密码</el-button>
          <el-button
            size="mini"
            type="danger"
            @click="deleteRow(scope.row.id)"
            v-if="userRole === 'admin'"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页和添加按钮同一行 -->
    <div style="margin: 18px 0; display: flex; align-items: center; justify-content: space-between;">
      <el-button
        type="primary"
        class="button"
        @click="openAddDialog"
        style="margin-bottom: 0"
      >
        添加用户
      </el-button>
      <el-pagination
        background
        layout="total, prev, pager, next, jumper"
        :total="total"
        :page-size="pageSize"
        :current-page.sync="currentPage"
        @current-change="handlePageChange"
        @size-change="handleSizeChange"
        :page-sizes="[5, 10, 20, 50]"
        style="display: inline-block;"
      />
    </div>

    <!-- 添加用户弹出层 -->
    <el-dialog
      :visible.sync="addDialogVisible"
      title="添加用户"
      width="520px"
      class="dark-detail-dialog"
      :close-on-click-modal="false"
      :close-on-press-escape="true"
      append-to-body
    >
      <div class="detail-content">
        <el-form :model="addForm" :rules="addRules" ref="addFormRef" label-width="100px" class="dark-edit-form">
          <el-form-item label="用户名" prop="name">
            <el-input v-model="addForm.name" placeholder="请输入用户名"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addForm.password" placeholder="请输入密码"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addForm.email" placeholder="请输入邮箱"></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="phone">
            <el-input v-model="addForm.phone" placeholder="请输入电话"></el-input>
          </el-form-item>
          <el-form-item label="地址" prop="address">
            <el-input v-model="addForm.address" placeholder="请输入地址"></el-input>
          </el-form-item>
          <el-form-item label="是否管理员" prop="isManager">
            <el-select v-model="addForm.isManager" placeholder="请选择是否管理员">
              <el-option label="是" value="1"></el-option>
              <el-option label="否" value="2"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false" class="dark-btn">取消</el-button>
        <el-button type="primary" @click="handleAddUser" class="dark-btn">保存</el-button>
      </span>
    </el-dialog>
  
    <!-- 编辑用户弹出层 -->
    <el-dialog
      :visible.sync="editDialogVisible"
      title="编辑用户"
      width="520px"
      class="dark-detail-dialog"
      :close-on-click-modal="false"
      :close-on-press-escape="true"
      append-to-body
    >
      <div class="detail-content">
        <el-form :model="editForm" :rules="editRules" ref="editFormRef" label-width="100px" class="dark-edit-form">
          <el-form-item label="用户名" prop="name">
            <el-input v-model="editForm.name" placeholder="请输入用户名"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editForm.email" placeholder="请输入邮箱"></el-input>
          </el-form-item>
        
          <el-form-item label="电话" prop="phone">
            <el-input v-model="editForm.phone" placeholder="请输入电话"></el-input>
          </el-form-item>
          <el-form-item label="地址" prop="address">
            <el-input v-model="editForm.address" placeholder="请输入地址"></el-input>
          </el-form-item>
    
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false" class="dark-btn">取消</el-button>
        <el-button type="primary" @click="handleEditUser" class="dark-btn">保存</el-button>
      </span>
    </el-dialog>
  
    <!-- 详情弹出层 -->
    <el-dialog
      :visible.sync="detailsDialogVisible"
      title="用户详情"
      width="520px"
      class="dark-detail-dialog"
      :close-on-click-modal="false"
      :close-on-press-escape="true"
      append-to-body
    >
      <div class="detail-content">
        <div class="detail-row">
          <span class="detail-label">用户名：</span>
          <span class="detail-value">{{ detailsForm.name }}</span>
        </div>
        <div class="detail-row">
          <span class="detail-label">邮箱：</span>
          <span class="detail-value">{{ detailsForm.email }}</span>
        </div>
        <div class="detail-row">
          <span class="detail-label">电话：</span>
          <span class="detail-value">{{ detailsForm.phone }}</span>
        </div>
        <div class="detail-row">
          <span class="detail-label">地址：</span>
          <span class="detail-value">{{ detailsForm.address }}</span>
        </div>
        <div class="detail-row">
          <span class="detail-label">是否管理员：</span>
          <span class="detail-value">{{ detailsForm.isManager == 1 ? '是' : '否' }}</span>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="detailsDialogVisible = false" class="dark-btn">关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import { usergetToolList, insertgetToolList, updategetToolList, deletegetToolList,editgetToolList } from "@/api/user/user.js"; // 引入用户相关的API接口
  import dayjs from "dayjs"; // 确保正确引入 dayjs
  import { mapState } from "vuex";
  export default {
    data() {
      return {
        userList: [], // 当前页用户数据
        allUserList: [], // 全部用户数据（如后端不支持分页时用）
        addDialogVisible: false,
        editDialogVisible: false,
        detailsDialogVisible: false,
        addForm: {
          name: "",
          email: "",
          phone: "",
          address: "",
          birthday:"",
          isManager: "",
        },
        editForm: {},
        detailsForm: {},
        addRules: {
          name: [{ required: true, message: "请输入用户名", trigger: "blur" }],
          password: [{ required: true, message: "请输入密码", trigger: "blur" }],
          isManager: [{ required: true, message: "请选择是否管理员", trigger: "change" }],
        },
        editRules: {
          name: [{ required: true, message: "请输入用户名", trigger: "blur" }],
          isManager: [{ required: true, message: "请选择是否管理员", trigger: "change" }],
        },
        // 分页相关
        currentPage: 1,
        pageSize: 10,
        total: 0,
      };
    },
    computed: {
      ...mapState(["userRole"])
    },
    mounted() {
      this.usergetTool();
    },
    methods: {
      editDetailsDialog(row){
        console.log("编辑用户数据:", row); // 确认数据
        let id = row.id; // 获取用户ID
        console.log(id);
        
        this.$prompt("请输入新密码", "修改密码", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          inputPattern: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,}$/,
          inputErrorMessage: "密码必须包含字母和数字，并且至少6位"
        }).then(({ value }) => {
          console.log("新密码:", value);
          const userData = {id, password: value};
          
          // 调用修改密码接口
          editgetToolList(userData).then(() => {
            this.$message.success("密码修改成功");
          }).catch(() => {
            this.$message.error("密码修改失败");
          });
        }).catch(() => {
          this.$message.info("取消修改");
        });
      },
      async usergetTool() {
        try {
          const response = await usergetToolList();
          // 假设后端返回数组，如果后端支持分页可直接赋值userList和total
          this.allUserList = Array.isArray(response) ? response : (response.data || []);
          this.total = this.allUserList.length;
          this.setPageData();
        } catch (error) {
          console.error("获取用户列表失败:", error);
        }
      },
      setPageData() {
        // 前端分页
        const start = (this.currentPage - 1) * this.pageSize;
        const end = start + this.pageSize;
        this.userList = this.allUserList.slice(start, end);
      },
      handlePageChange(page) {
        this.currentPage = page;
        this.setPageData();
      },
      handleSizeChange(size) {
        this.pageSize = size;
        this.currentPage = 1;
        this.setPageData();
      },
      openAddDialog() {
        this.addDialogVisible = true; // 打开添加用户弹出层
        if (this.$refs.addFormRef) {
          this.$refs.addFormRef.resetFields(); // 重置表单
        }
      },
      async handleAddUser() {
        if (this.addForm.birthday) {
          this.addForm.birthday = dayjs(this.addForm.birthday).format("YYYY-MM-DD HH:mm:ss");
        }
        try {
          await this.$refs.addFormRef.validate();
          const response = await insertgetToolList(this.addForm);
          this.$message.success("用户添加成功");
          this.addDialogVisible = false;
          await this.usergetTool();
        } catch (error) {
          this.$message.error("用户添加失败，请稍后再试");
        }
      },
      openEditDialog(row) {
        this.editForm = { ...row }; // 数据回显
        this.editDialogVisible = true; // 打开编辑用户弹出层
      },
      async handleEditUser() {
       
        if (this.editForm.birthday) {
          this.editForm.birthday = dayjs(this.editForm.birthday).format("YYYY-MM-DD HH:mm:ss");
        }
        console.log("编辑用户数据:213213", this.editForm); // 确认数据
        try {
          await this.$refs.editFormRef.validate();
          const response = await updategetToolList(this.editForm);
          this.$message.success("用户编辑成功");
          this.editDialogVisible = false;
          await this.usergetTool();
        } catch (error) {
          this.$message.error("用户编辑失败，请稍后再试");
        }
      },
      openDetailsDialog(row) {
        this.detailsForm = { ...row }; // 数据回显
        this.detailsDialogVisible = true; // 打开详情弹出层
      },
      async deleteRow(id) {
        try {
          await this.$confirm("此操作将永久删除该条记录, 是否继续?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          });
          const response = await deletegetToolList(id);
          this.$message.success("用户删除成功");
          await this.usergetTool();
        } catch (error) {
          this.$message.error("用户删除失败，请稍后再试");
        }
      },
    },
  };
  </script>
  
  <style scoped>
.center-table .el-table__cell {
  text-align: center;
}

.dialog-footer {
  text-align: right;
}

.ellipsis {
  display: inline-block;
  max-width: 150px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.center-table {
  background: #f8fafc !important;
  border-radius: 10px !important;
  color: #232526 !important;
  box-shadow: 0 2px 12px #b3c6e822;
}

.center-table ::v-deep .el-table__header,
.center-table ::v-deep .el-table__body {
  background: #f8fafc !important;
  color: #409eff !important;
}

.center-table ::v-deep th,
.center-table ::v-deep td {
  background: #f8fafc !important;
  color: #232526 !important;
  border-bottom: 1px solid #b3c6e8 !important;
}

.center-table ::v-deep .el-table__row:hover>td {
  background: #e9f0fb !important;
  color: #409eff !important;
}

.center-table ::v-deep .el-table__body tr.current-row>td {
  background: #e9f0fb !important;
  color: #409eff !important;
}

.center-table ::v-deep .el-table__body-wrapper {
  border-radius: 10px !important;
}

.center-table ::v-deep .el-table__column-resize {
  background: #409eff !important;
}

.center-table ::v-deep .el-table__row .el-checkbox__input.is-checked .el-checkbox__inner {
  background: #409eff !important;
  border-color: #53caff !important;
}

.center-table ::v-deep .el-checkbox__inner {
  background: #f8fafc !important;
  border: 1.5px solid #409eff !important;
}

.center-table ::v-deep .el-checkbox__input.is-checked .el-checkbox__inner::after {
  border-color: #fff !important;
}

.dark-detail-dialog ::v-deep .el-dialog__header,
.dark-detail-dialog ::v-deep .el-dialog__body,
.dark-detail-dialog ::v-deep .el-dialog__footer {
  background: #f8fafc !important;
  color: #232526 !important;
  border-radius: 14px;
  border: 1.5px solid #b3c6e8;
}

.dark-detail-dialog ::v-deep .el-dialog {
  border-radius: 14px;
  border: 1.5px solid #b3c6e8;
  background: #f8fafc !important;
}

.dark-detail-dialog ::v-deep .el-dialog__title {
  color: #409eff !important;
  font-weight: bold;
  font-size: 18px;
  letter-spacing: 1px;
}

.detail-content {
  padding: 18px 8px 8px 8px;
  background: #fff;
  border-radius: 10px;
  color: #232526;
  box-shadow: 0 1px 8px #b3c6e822;
}

.detail-row {
  display: flex;
  align-items: center;
  margin-bottom: 14px;
}

.detail-label {
  min-width: 90px;
  color: #409eff;
  font-weight: 600;
  font-size: 15px;
  letter-spacing: 1px;
}

.detail-value {
  color: #232526;
  font-size: 15px;
  word-break: break-all;
}

.dark-edit-form ::v-deep .el-form-item__label {
  color: #409eff !important;
}

.dark-edit-form ::v-deep .el-input__inner,
.dark-edit-form ::v-deep .el-select .el-input__inner {
  background: #fff !important;
  color: #232526 !important;
  border: 1px solid #b3c6e8 !important;
}

.dark-edit-form ::v-deep .el-input__inner:focus,
.dark-edit-form ::v-deep .el-select .el-input__inner:focus {
  border-color: #409eff !important;
  background: #f3f6fa !important;
}

.dark-btn {
  background: linear-gradient(90deg, #409eff 60%, #53caff 100%) !important;
  color: #fff !important;
  border: none !important;
  border-radius: 8px !important;
  font-weight: 600;
  font-size: 15px;
  padding: 8px 22px;
  transition: background 0.18s, box-shadow 0.18s;
}

.dark-btn:hover {
  background: linear-gradient(90deg, #53caff 60%, #409eff 100%) !important;
  color: #fff !important;
  box-shadow: 0 4px 18px #b3c6e822;
}
</style>
